package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Author YWB
 * @Date 2021/1/15
 * desc 静态资源请求处理工具类
 **/
public class StaticResourceUtil {
    /**
     * 获取静态资源的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\","/")+path;
    }

    /**
     * 读取静态文件输入流，通过输出流输出
     * @param inputStream
     * @param outputStream
     * @throws IOException
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count=0;
        while (count==0){
            count=inputStream.available();
        }
        int resourceSize=count;
        //先输出HTTP请求头信息
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        //读取内容输出
        long written=0;
        //计划每次缓冲的长度
        int byteSize=1024;
        byte[] bytes = new byte[byteSize];
        while (written<resourceSize){
            //剩余未读取的内容大小不足1024，按真实长度处理
            if(written+byteSize>resourceSize){
                //剩余文件内容长度
                byteSize=(int) (resourceSize-written);
                bytes=new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written+=byteSize;
        }
    }
}
